<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/user'
import { useMerchantStore } from '@/stores/merchant'
import { IconSearch, IconMenu, IconClose, IconHome, IconUser, IconCalendar, IconDashboard, IconExport, IconDown, IconPlus } from '@arco-design/web-vue/es/icon'

// 购物车图标使用自定义HTML
const cartIconSvg = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <circle cx="9" cy="21" r="1"></circle>
  <circle cx="20" cy="21" r="1"></circle>
  <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>`

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const merchantStore = useMerchantStore()
const collapsed = ref(false)
const isMobile = ref(false)
const showMobileMenu = ref(false)

// 获取购物车数据
const cartItems = ref<Array<{dishId: number, dishSpecId?: number, quantity: number, price?: number}>>([])
const cartTotal = ref(0)

// 计算购物车中的商品总数
const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 获取购物车数据
const getCartData = () => {
  // 从localStorage获取所有购物车数据
  const cartData: Record<string, Array<{dishId: number, dishSpecId?: number, quantity: number, price?: number}>> = {}
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key && key.startsWith('cart_')) {
      try {
        const items = JSON.parse(localStorage.getItem(key) || '[]')
        cartData[key] = items
      } catch (e) {
        console.error('解析购物车数据失败:', e)
      }
    }
  }
  
  // 合并所有购物车数据
  let allItems: Array<{dishId: number, dishSpecId?: number, quantity: number, price?: number}> = []
  let total = 0
  
  Object.values(cartData).forEach(items => {
    if (Array.isArray(items)) {
      allItems = [...allItems, ...items]
      items.forEach(item => {
        total += (item.price || 0) * item.quantity
      })
    }
  })
  
  cartItems.value = allItems
  cartTotal.value = total
}

// 检测屏幕尺寸
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768
}

// 确保在组件加载时获取用户信息
onMounted(async () => {
  if (userStore.isLoggedIn && !userStore.currentUser) {
    await userStore.fetchCurrentUser()
  }
  if (merchantStore.isLoggedIn && !merchantStore.currentMerchant) {
    await merchantStore.fetchCurrentMerchant()
  }
  
  // 初始化检测屏幕尺寸
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
  
  // 获取购物车数据
  getCartData()
  
  // 监听storage事件，当购物车数据变化时更新
  window.addEventListener('storage', getCartData)
})

// 监听登录状态变化
watch(() => userStore.isLoggedIn, async (isLoggedIn) => {
  if (isLoggedIn && !userStore.currentUser) {
    await userStore.fetchCurrentUser()
  }
}, { immediate: true })

watch(() => merchantStore.isLoggedIn, async (isLoggedIn) => {
  if (isLoggedIn && !merchantStore.currentMerchant) {
    await merchantStore.fetchCurrentMerchant()
  }
}, { immediate: true })

// 切换移动端菜单
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

// 关闭移动端菜单
const closeMobileMenu = () => {
  showMobileMenu.value = false
}

// 退出登录
const handleLogout = () => {
  userStore.logout()
  Message.success('退出登录成功')
  router.push('/')
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
  closeMobileMenu()
}

// 跳转到注册页
const goToRegister = () => {
  router.push('/register')
  closeMobileMenu()
}

// 跳转到个人中心
const goToUserCenter = () => {
  router.push('/user')
  closeMobileMenu()
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
  closeMobileMenu()
}

// 跳转到订单页
const goToOrder = () => {
  router.push('/order')
  closeMobileMenu()
}

// 跳转到商家登录页
const goToMerchantLogin = () => {
  router.push('/merchant/login')
  closeMobileMenu()
}

// 跳转到商家注册页
const goToMerchantRegister = () => {
  router.push('/merchant/register')
  closeMobileMenu()
}

// 跳转到商家管理中心
const goToMerchantDashboard = () => {
  router.push('/merchant/dashboard')
  closeMobileMenu()
}

// 跳转到购物车页面
const goToCart = () => {
  router.push('/cart')
  closeMobileMenu()
}
</script>

<template>
  <div class="app-container">
    <header class="header">
      <div class="container header-container">
        <div class="logo" @click="goToHome">
          <i class="icon-shop"></i>
          <span>康赟点餐系统</span>
        </div>
        
        <!-- 移动端菜单按钮 -->
        <div class="mobile-menu-toggle" v-if="isMobile" @click="toggleMobileMenu">
          <icon-menu />
        </div>
        
        <!-- 桌面端导航 -->
        <nav class="nav-desktop" v-if="!isMobile">
          <a-space>
            <!-- 用户已登录 -->
            <template v-if="userStore.isLoggedIn">
              <a-button type="text" @click="goToUserCenter" class="nav-button">
                <template #icon><icon-user /></template>
                个人中心
              </a-button>
              
              <a-button type="text" @click="goToOrder" class="nav-button">
                <template #icon><icon-calendar /></template>
                我的订单
              </a-button>
              
              <a-dropdown trigger="click">
                <a-avatar class="user-avatar">
                  <template #icon><icon-user /></template>
                </a-avatar>
                <template #content>
                  <a-doption @click="goToUserCenter">
                    <template #icon><icon-user /></template>
                    个人中心
                  </a-doption>
                  <a-doption @click="goToOrder">
                    <template #icon><icon-calendar /></template>
                    我的订单
                  </a-doption>
                  <a-doption @click="handleLogout">
                    <template #icon><icon-export /></template>
                    退出登录
                  </a-doption>
                </template>
              </a-dropdown>
              <span class="user-name">{{ userStore.currentUser?.nickname || userStore.currentUser?.username }}</span>
            </template>
            
            <!-- 商家已登录 -->
            <template v-else-if="merchantStore.isLoggedIn">
              <a-button type="text" @click="goToMerchantDashboard" class="nav-button">
                <template #icon><icon-dashboard /></template>
                商家管理中心
              </a-button>
              
              <a-dropdown trigger="click">
                <a-avatar class="user-avatar">
                  <template #icon><icon-user /></template>
                </a-avatar>
                <template #content>
                  <a-doption @click="goToMerchantDashboard">
                    <template #icon><icon-dashboard /></template>
                    商家管理中心
                  </a-doption>
                  <a-doption @click="merchantStore.logout">
                    <template #icon><icon-export /></template>
                    退出登录
                  </a-doption>
                </template>
              </a-dropdown>
              <span class="user-name">{{ merchantStore.currentMerchant?.name }}</span>
            </template>
            
            <!-- 未登录 -->
            <template v-else>
              <a-dropdown trigger="click">
                <a-button type="text" class="nav-button">
                  商家入口
                  <template #icon><icon-down /></template>
                </a-button>
                <template #content>
                  <a-doption @click="goToMerchantLogin">
                    <template #icon><icon-user /></template>
                    商家登录
                  </a-doption>
                  <a-doption @click="goToMerchantRegister">
                    <template #icon><icon-plus /></template>
                    商家注册
                  </a-doption>
                </template>
              </a-dropdown>
              
              <a-button type="text" @click="goToLogin" class="nav-button">登录</a-button>
              <a-button type="primary" @click="goToRegister">注册</a-button>
            </template>
          </a-space>
        </nav>
      </div>
      
      <!-- 移动端导航菜单 -->
      <div class="nav-mobile" v-if="isMobile" :class="{ 'active': showMobileMenu }">
        <div class="mobile-menu-header">
          <div class="logo">康赟点餐系统</div>
          <a-button class="close-menu" @click="closeMobileMenu">
            <template #icon><icon-close /></template>
          </a-button>
        </div>
        
        <div class="mobile-menu-content">
          <!-- 用户已登录 -->
          <template v-if="userStore.isLoggedIn">
            <div class="mobile-user-info">
              <a-avatar class="user-avatar">
                <template #icon><icon-user /></template>
              </a-avatar>
              <span class="user-name">{{ userStore.currentUser?.nickname || userStore.currentUser?.username }}</span>
            </div>
            <a-menu>
              <a-menu-item @click="goToHome">
                <template #icon><icon-home /></template>
                首页
              </a-menu-item>
              <a-menu-item @click="goToUserCenter">
                <template #icon><icon-user /></template>
                个人中心
              </a-menu-item>
              <a-menu-item @click="goToOrder">
                <template #icon><icon-calendar /></template>
                我的订单
              </a-menu-item>
              <a-menu-item @click="handleLogout">
                <template #icon><icon-export /></template>
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
          
          <!-- 商家已登录 -->
          <template v-else-if="merchantStore.isLoggedIn">
            <div class="mobile-user-info">
              <a-avatar class="user-avatar">
                <template #icon><icon-user /></template>
              </a-avatar>
              <span class="user-name">{{ merchantStore.currentMerchant?.name }}</span>
            </div>
            <a-menu>
              <a-menu-item @click="goToHome">
                <template #icon><icon-home /></template>
                首页
              </a-menu-item>
              <a-menu-item @click="goToMerchantDashboard">
                <template #icon><icon-dashboard /></template>
                商家管理中心
              </a-menu-item>
              <a-menu-item @click="merchantStore.logout">
                <template #icon><icon-export /></template>
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
          
          <!-- 未登录 -->
          <template v-else>
            <a-menu>
              <a-menu-item @click="goToHome">
                <template #icon><icon-home /></template>
                首页
              </a-menu-item>
              <a-menu-item @click="goToLogin">
                <template #icon><icon-user /></template>
                用户登录
              </a-menu-item>
              <a-menu-item @click="goToRegister">
                <template #icon><icon-plus /></template>
                用户注册
              </a-menu-item>
              <a-sub-menu>
                <template #title>
                  <icon-user />
                  商家入口
                </template>
                <a-menu-item @click="goToMerchantLogin">商家登录</a-menu-item>
                <a-menu-item @click="goToMerchantRegister">商家注册</a-menu-item>
              </a-sub-menu>
            </a-menu>
          </template>
        </div>
      </div>
    </header>
    
    <!-- 固定在右侧的购物车 -->
    <div class="cart-sidebar">
      <a-button shape="circle" class="cart-button" type="primary" @click="goToCart">
        <span v-html="cartIconSvg" class="cart-icon"></span>
        <span v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</span>
      </a-button>
      <div class="cart-total" v-if="cartTotal > 0">¥{{ cartTotal.toFixed(2) }}</div>
    </div>
    
    <main class="main-content">
      <div class="container">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </div>
    </main>
    
    <footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-logo">
            <icon-user />
            <span>康赟点餐系统</span>
          </div>
          <div class="footer-links">
            <a href="#">关于我们</a>
            <a href="#">联系方式</a>
            <a href="#">帮助中心</a>
            <a href="#">隐私政策</a>
          </div>
          <div class="footer-copyright">
            <p>© {{ new Date().getFullYear() }} 康赟点餐系统 - 软件服务工程课程项目</p>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.header {
  background-color: var(--bg-color-light);
  box-shadow: var(--box-shadow-light);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
  padding: 0 var(--spacing-md);
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  color: var(--primary-color);
  cursor: pointer;
  transition: var(--transition-normal);
}

.logo:hover {
  color: var(--primary-light);
}

.logo i {
  margin-right: var(--spacing-xs);
  font-size: 24px;
}

.nav-desktop {
  display: flex;
  align-items: center;
}

.nav-button {
  padding: var(--spacing-xs) var(--spacing-sm);
  color: var(--text-secondary);
  transition: var(--transition-normal);
}

.nav-button:hover {
  color: var(--primary-color);
}

.user-avatar {
  background-color: var(--primary-light);
  cursor: pointer;
}

.user-name {
  margin-left: var(--spacing-xs);
  color: var(--text-secondary);
  font-weight: 500;
}

/* 移动端菜单 */
.mobile-menu-toggle {
  font-size: 24px;
  cursor: pointer;
  color: var(--text-secondary);
}

.nav-mobile {
  position: fixed;
  top: 0;
  right: -280px;
  width: 280px;
  height: 100vh;
  background-color: var(--bg-color-light);
  box-shadow: var(--box-shadow);
  z-index: 1000;
  transition: right 0.3s ease;
  overflow-y: auto;
}

.nav-mobile.active {
  right: 0;
}

.mobile-menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
}

.close-menu {
  font-size: 20px;
}

.mobile-menu-content {
  padding: var(--spacing-md) 0;
}

.mobile-user-info {
  display: flex;
  align-items: center;
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
}

.mobile-user-info .user-name {
  margin-left: var(--spacing-md);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: var(--spacing-lg) 0;
  background-color: var(--bg-color);
}

/* 页脚 */
.footer {
  background-color: var(--bg-color-light);
  border-top: 1px solid var(--border-color);
  padding: var(--spacing-lg) 0;
}

.footer-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-md);
}

.footer-logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: var(--primary-color);
}

.footer-logo i {
  margin-right: var(--spacing-xs);
  font-size: 20px;
}

.footer-links {
  display: flex;
  gap: var(--spacing-lg);
}

.footer-links a {
  color: var(--text-secondary);
  text-decoration: none;
  transition: var(--transition-normal);
}

.footer-links a:hover {
  color: var(--primary-color);
}

.footer-copyright {
  color: var(--text-disabled);
  font-size: 14px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-container {
    height: 56px;
  }
  
  .logo {
    font-size: 18px;
  }
  
  .footer-links {
    flex-wrap: wrap;
    justify-content: center;
    gap: var(--spacing-md);
  }
}

/* 购物车侧边栏 */
.cart-sidebar {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-sm);
  z-index: 90;
}

.cart-button {
  width: 50px;
  height: 50px;
  position: relative;
  box-shadow: var(--box-shadow);
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-icon svg {
  width: 100%;
  height: 100%;
  stroke: currentColor;
}

.cart-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: var(--danger-color);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-total {
  background-color: var(--bg-color-light);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  font-weight: bold;
  color: var(--danger-color);
  box-shadow: var(--box-shadow-light);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .cart-sidebar {
    bottom: 80px;
    top: auto;
    right: 20px;
    transform: none;
  }
}
</style> 